package com.selfdriving.activity;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.selfdriving.BaseFragmentActivity;
import com.selfdriving.R;
import com.selfdriving.bean.Entity;
import com.selfdriving.bean.MyFile;
import com.selfdriving.bean.WriteScenic;
import com.selfdriving.dialog.ChooseDialog;
import com.selfdriving.dialog.ChooseDialog.OnBirthdayDialogClickListener;
import com.selfdriving.dialog.EntityListDialogAdapter;
import com.selfdriving.utils.BitmapUtil;
import com.selfdriving.utils.Constant;
import com.selfdriving.utils.WriteCamera;
import com.selfdriving.wl.activity.SimpleListDialog;
import com.selfdriving.wl.activity.SimpleListDialog.onSimpleListItemClickListener;

public class ActivityWriteTravelNotes extends BaseFragmentActivity implements
		OnClickListener
{
	private ImageView goBreak;
	private TextView topText;
	private Button confirm;
	EditText titleText;
	EditText Msg;
	ImageButton addImg1;
	ImageButton addImg2;
	ImageButton addImg3;
	ImageButton addImg;
	ImageButton addImgShow;
	LinearLayout setScenic;
	LinearLayout setScenicMode;
	TextView setMyScenic;
	TextView setMyScenicMode;
	Button clean;
	private SimpleListDialog mSimpleListDialog;
	private ChooseDialog chooseDialog;
	List<Entity> scenicList = new ArrayList<Entity>();
	List<Bitmap> bitMapList = new ArrayList<Bitmap>();
	List<String> uriList = new ArrayList<String>();
	String id;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		super.setContentView(R.layout.activity_release);
		initViews();
		initEvents();
	}

	@Override
	protected void initViews()
	{
		// TODO Auto-generated method stub
		setScenicMode = (LinearLayout) findViewById(R.id.setScenicMode);
		setMyScenicMode = (TextView) findViewById(R.id.setMyScenicMode);
		setMyScenic = (TextView) findViewById(R.id.setMyScenic);
		setScenic = (LinearLayout) findViewById(R.id.setScenic);
		confirm = (Button) findViewById(R.id.top_right_but);
		goBreak = (ImageView) findViewById(R.id.head_break);
		topText = (TextView) findViewById(R.id.top_text_middle);
		topText.setText("景点随写");
		confirm.setVisibility(View.VISIBLE);
		goBreak.setVisibility(View.VISIBLE);
		titleText = (EditText) findViewById(R.id.release_title);
		Msg = (EditText) findViewById(R.id.release_msg);
		addImg1 = (ImageButton) findViewById(R.id.release_addimg1);
		addImg2 = (ImageButton) findViewById(R.id.release_addimg2);
		addImg3 = (ImageButton) findViewById(R.id.release_addimg3);
		clean = (Button) findViewById(R.id.release_clean);
		confirm.setText("确定");
		setMyScenicMode.setText("游记");
	}

	@Override
	protected void initEvents()
	{
		clean.setOnClickListener(this);
		goBreak.setOnClickListener(this);
		setScenicMode.setOnClickListener(this);
		setScenic.setOnClickListener(this);
		addImg1.setOnClickListener(this);
		addImg2.setOnClickListener(this);
		addImg3.setOnClickListener(this);
		confirm.setOnClickListener(this);
	}

	@Override
	public void onClick(View v)
	{
		// TODO Auto-generated method stub
		switch (v.getId())
		{
		case R.id.release_addimg1:
			addImg = addImg1;
			addImgShow = addImg2;
			new WriteCamera(ActivityWriteTravelNotes.this,
					ActivityWriteTravelNotes.this);
			break;
		case R.id.release_addimg2:
			addImg = addImg2;
			addImgShow = addImg3;
			new WriteCamera(ActivityWriteTravelNotes.this,
					ActivityWriteTravelNotes.this);
			break;
		case R.id.release_addimg3:
			addImg = addImg3;
			new WriteCamera(ActivityWriteTravelNotes.this,
					ActivityWriteTravelNotes.this);
			break;
		case R.id.release_clean:
			bitMapList.clear();
			uriList.clear();
			addImg1.setImageResource(R.drawable.btn_photo);
			addImg2.setImageResource(R.drawable.btn_photo);
			addImg3.setImageResource(R.drawable.btn_photo);
			addImg2.setVisibility(View.GONE);
			addImg3.setVisibility(View.GONE);
			break;
		case R.id.top_right_but:
			PostScenicDatas();
			break;
		case R.id.setScenic:
			getScenicDatas();
			break;
		case R.id.head_break:
			finish();
			break;
		case R.id.setScenicMode:
			chooseDialog = new ChooseDialog(mApplication, this, "选择文章类型");
			chooseDialog
					.setOnBirthdayDialogClickListener(new OnBirthdayDialogClickListener()
					{
						@Override
						public void OnOkClick(String st)
						{
							setMyScenicMode.setText(st);
							chooseDialog.dismiss();
						}
					});
			chooseDialog.show();
			break;
		}
	}

	private class ListOnSimpleListItemClickListener implements
			onSimpleListItemClickListener
	{
		@Override
		public void onItemClick(int position)
		{
			WriteScenic scenic = (WriteScenic) scenicList.get(position);
			String st = scenic.getName();
			setMyScenic.setText(st);
			id = scenic.getId();
		}
	}

	public String getRealPathFromURI(Uri contentUri)
	{
		String res = null;
		if (contentUri != null)
		{
			String[] proj = { MediaStore.Images.Media.DATA };
			Cursor cursor = getContentResolver().query(contentUri, proj, null,
					null, null);
			if (cursor != null)
			{
				if (cursor.moveToFirst())
				{
					int column_index = cursor
							.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
					res = cursor.getString(column_index);
				}
				cursor.close();
			}
		}
		return res;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		super.onActivityResult(requestCode, resultCode, data);
		try
		{
			if (resultCode != Activity.RESULT_OK)
			{
				return;
			}
			switch (requestCode)
			{
			case Constant.PICK_FROM_FILE:// 取得本地图片
				Constant.imageCaptureUri = data.getData();
				Constant.fileRealPath = getRealPathFromURI(Constant.imageCaptureUri);
				Bitmap bitmap = BitmapUtil
						.getSamplingImage(Constant.fileRealPath);
				if (bitmap != null)
				{
					addImg.setImageBitmap(bitmap);
					addImgShow.setVisibility(View.VISIBLE);
					bitMapList.add(bitmap);
					uriList.add(Constant.fileRealPath);
				}
				break;
			case Constant.PICK_FROM_CAMERA:// 拍照
				Constant.fileRealPath = Constant.imageCaptureUri.getPath();
				bitmap = BitmapUtil.getSamplingImage(Constant.fileRealPath);
				if (bitmap != null)
				{
					addImg.setImageBitmap(bitmap);
					addImgShow.setVisibility(View.VISIBLE);
					bitMapList.add(bitmap);
					uriList.add(Constant.fileRealPath);
				}
				break;
			}
		} catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	public void getScenicDatas()
	{
		scenicList.clear();
		showLoadingDialog("景点信息获取中...");
		AjaxParams params = new AjaxParams();
		params.put("f", "10");
		FinalHttp fh = new FinalHttp();
		fh.configTimeout(10000);
		fh.post(Constant.POST, params, new AjaxCallBack<Object>()
		{
			@Override
			public void onFailure(Throwable t, String strMsg)
			{
				showShortToast("获取景点信息失败");
				dismissLoadingDialog();
			}

			@Override
			public void onSuccess(Object o)
			{
				String json = o.toString();
				try
				{
					JSONArray jsonArray = new JSONArray(json);
					WriteScenic scenic;
					for (int i = 0; i < jsonArray.length(); i++)
					{
						JSONObject jsonObject = jsonArray.getJSONObject(i);
						String id = jsonObject.getString("id");
						String name = jsonObject.getString("name");
						scenic = new WriteScenic(name, id);
						scenicList.add(scenic);
					}
				} catch (JSONException e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				mSimpleListDialog = new SimpleListDialog(
						ActivityWriteTravelNotes.this);
				mSimpleListDialog.setTitle("选择要发布到的景点");
				mSimpleListDialog.setTitleLineVisibility(View.GONE);
				mSimpleListDialog
						.setAdapter(new EntityListDialogAdapter(mApplication,
								ActivityWriteTravelNotes.this, scenicList));
				mSimpleListDialog
						.setOnSimpleListItemClickListener(new ListOnSimpleListItemClickListener());
				mSimpleListDialog.show();
				dismissLoadingDialog();
			}
		});
	}

	public void PostScenicDatas()
	{
		String title = titleText.getText().toString();
		String content = Msg.getText().toString();
		String type = setMyScenicMode.getText().toString();
		if (id == null || id.equals(""))
		{
			showShortToast("请选择要发布到的景点");
			return;
		}
		if (title == null || title.equals(""))
		{
			showShortToast("请输入标题");
			return;
		}
		if (content == null || content.equals(""))
		{
			showShortToast("请输入随写内容");
			return;
		}
		if (uriList.size() < 1)
		{
			showShortToast("请添加图片");
			return;
		}
		String types = "0";
		showLoadingDialog(type + "发布中...");
		List<MyFile> fileList = new ArrayList<MyFile>();
		for (int i = 0; i < uriList.size(); i++)
		{
			fileList.add(new MyFile("img" + i, new File(uriList.get(i))));
		}
		if (type.equals("游记"))
		{
			types = "0";
		} else if (type.equals("攻略"))
		{
			types = "1";
		}
		AjaxParams params = new AjaxParams();
		params.put("f", "21");
		params.put("sid", id);
		params.put("title", title);
		params.put("phone", mApplication.user == null ? "13627910370"
				: mApplication.user.phone);
		params.put("types", types);
		params.put("content", content);
		try
		{
			for (MyFile myFile : fileList)
			{
				params.put(myFile.getFileName(), myFile.getFile()); // 上传文件
				System.out.println("myFile.getFileName()"
						+ myFile.getFileName() + "/myFile.getFile()"
						+ myFile.getFile());
			}
		} catch (FileNotFoundException e)
		{
			e.printStackTrace();
		}
		FinalHttp fh = new FinalHttp();
		fh.configTimeout(30000);
		fh.post(Constant.POST, params, new AjaxCallBack<Object>()
		{
			@Override
			public void onFailure(Throwable t, String strMsg)
			{
				showShortToast("发布失败");
				dismissLoadingDialog();
			}

			@Override
			public void onSuccess(Object o)
			{

				String json = o.toString();
				if (json.contains("000000"))
				{
					showShortToast("发布成功");
					setResult(RESULT_OK);
					finish();
				} else
				{
					showShortToast("发布失败");
				}
				dismissLoadingDialog();
			}
		});
	}
}
